import axios from 'axios'
import {Message
                    
} from 'element-ui'
import router from '@/router/index'
import {
  getToken
} from '@/utils/auth'
// create an axios instance
const service = axios.create({
  baseURL: "/api", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    "content-type": "application/x-www-form-urlencoded"
  },
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  res => {
    if (res.data.status == 403) {
      Message({
        message: res.data.msg,
        type: 'warning',
        duration: 5 * 1000
      })
      router.push("/login");
      return Promise.reject(new Error(res.message || 'Error'))

    } else if (res.data == "服务器异常！") {
      Message({
        message: res.data,
        type: 'warning',
        duration: 5 * 1000

      })
      return Promise.reject(new Error(res.message || 'Error'))

    } else if (res.data.event && res.data.event < 0) {
      Message({
        message: res.data.message,
        type: 'warning',
        duration: 5 * 1000
      })
    } else {
      return res.data
    }
  },
  error => {
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error.response.data)
  }
)

export default service